package service

import (
	"go-gin-demo/dao/mysql"
	"go-gin-demo/models"
	"go-gin-demo/pkg/jwt"
	"go-gin-demo/pkg/snowflake"
)

func SignUp(p *models.ParamSignUp) (err error) {
	// 判断用户是否存在
	if err = mysql.CheckUserExist(p.Username); err != nil {
		return err
	}

	// 生成UID
	userID := snowflake.GenID()

	// 构造一个用户
	u := &models.User{
		UserID:   userID,
		Username: p.Username,
		Passwd:   p.Passwd,
	}

	// 保存进数据库
	return mysql.InsertUser(u)
}

func Login(p *models.ParamLogin) (aToken, rToken string, err error) {
	user := &models.User{
		Username: p.Username,
		Passwd:   p.Passwd,
	}
	if err = mysql.Login(user); err != nil {
		return
	}
	// 生成 JWT
	aToken, rToken, err = jwt.GenToken(user.UserID)
	return
}

func RefreshToken(p *models.ParamRefreshToken) (aToken string, err error) {
	return jwt.RefreshToken(p.AToken, p.RToken)
}
